import React, { useState, useEffect } from "react";
import {
  Layout as AntLayout,
  Menu,
  theme,
  Typography,
  Avatar,
  Space,
  Drawer,
  Button,
} from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import {
  DashboardOutlined,
  ProjectOutlined,
  UserOutlined,
  MenuOutlined,
} from "@ant-design/icons";
import { Film } from "lucide-react";
import { usePermissions } from "@/contexts/PermissionContext";
import UserProfile from "./UserProfile";

const { Header, Content } = AntLayout;
const { Title, Text } = Typography;

interface LayoutProps {
  children: React.ReactNode;
}

const Layout: React.FC<LayoutProps> = ({ children }) => {
  const [mobileMenuVisible, setMobileMenuVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  // 获取权限信息
  const { hasPermission } = usePermissions();

  // 基础菜单项
  const baseMenuItems = [
    {
      key: "/",
      icon: <DashboardOutlined />,
      label: "仪表盘",
    },
    {
      key: "/create",
      icon: <ProjectOutlined />,
      label: "开始创作",
    },
    {
      key: "/projects",
      icon: <ProjectOutlined />,
      label: "项目管理",
    },
  ];

  // 管理员菜单项
  const adminMenuItems = [
    {
      key: "/users",
      icon: <UserOutlined />,
      label: "用户管理",
      requiresPermission: "can_manage_users" as const,
    },
  ];

  // 根据权限过滤菜单项
  const getFilteredMenuItems = () => {
    const menuItems = [...baseMenuItems];

    adminMenuItems.forEach((item) => {
      if (hasPermission(item.requiresPermission)) {
        menuItems.push({
          key: item.key,
          icon: item.icon,
          label: item.label,
        });
      }
    });

    return menuItems;
  };

  const menuItems = getFilteredMenuItems();

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 1200);
    };

    checkIsMobile();
    window.addEventListener("resize", checkIsMobile);

    return () => window.removeEventListener("resize", checkIsMobile);
  }, []);

  const handleMenuClick = ({ key }: { key: string }) => {
    navigate(key);
    setMobileMenuVisible(false);
    setDrawerVisible(false); // 关闭抽屉
  };

  return (
    <AntLayout style={{ minHeight: "100vh" }}>
      {/* 顶部导航栏 */}
      <Header
        style={{
          position: "fixed",
          top: 0,
          zIndex: 1000,
          width: "100%",
          padding: "0 24px",
          background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
          borderBottom: "none",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
          height: "64px",
        }}
      >
        {/* 左侧：Logo 和导航菜单 */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            flex: 1,
            height: "100%",
          }}
        >
          {/* Logo 区域 */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              marginRight: isMobile ? "16px" : "32px", // 移动端减少间距
              cursor: "pointer",
              height: "100%",
              minWidth: isMobile ? "150px" : "200px", // 移动端减少最小宽度
            }}
            onClick={() => navigate("/")}
          >
            <Avatar
              size={32}
              style={{
                background: "rgba(255, 255, 255, 0.2)",
                marginRight: "12px",
              }}
              icon={<Film size={16} color="white" />}
            />
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
              }}
            >
              <Title
                level={5}
                style={{
                  margin: 0,
                  color: "white",
                  lineHeight: "20px",
                }}
              >
                剪映助手
              </Title>
              <Text
                style={{
                  fontSize: "12px",
                  lineHeight: "12px",
                  color: "rgba(255, 255, 255, 0.8)",
                }}
              >
                v1.0.0
              </Text>
            </div>
          </div>

          {/* 桌面端导航菜单 */}
          {!isMobile && (
            <div className="desktop-menu" style={{ flex: 1 }}>
              <Menu
                mode="horizontal"
                selectedKeys={[location.pathname]}
                items={menuItems}
                onClick={handleMenuClick}
                style={{
                  border: "none",
                  background: "transparent",
                  height: "64px",
                  lineHeight: "64px",
                }}
                theme="dark"
              />
            </div>
          )}

          {/* 移动端菜单按钮 */}
          {isMobile && (
            <Button
              type="text"
              icon={<MenuOutlined style={{ color: "white", fontSize: "18px" }} />}
              onClick={() => setDrawerVisible(true)}
              style={{
                fontSize: "18px",
                height: "40px",
                width: "40px",
                color: "white",
                border: "none",
                backgroundColor: "rgba(255, 255, 255, 0.1)",
              }}
            />
          )}
        </div>

        {/* 右侧：用户信息 */}
        <div
          style={{
            minWidth: isMobile ? "120px" : "200px", // 移动端减少最小宽度
            display: "flex",
            justifyContent: "flex-end",
          }}
        >
          <div
            style={{
              filter: "drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1))",
              color: "white",
            }}
          >
            <UserProfile />
          </div>
        </div>
      </Header>

      {/* 移动端抽屉菜单 */}
      <Drawer
        title="导航菜单"
        placement="left"
        closable={true}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        styles={{
          body: { padding: 0 },
        }}
        width={window.innerWidth < 576 ? "280px" : "320px"}
      >
        <Menu
          mode="vertical"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={handleMenuClick}
          style={{ border: "none" }}
        />
      </Drawer>

      {/* 主内容区域 */}
      <Content
        style={{
          marginTop: "64px", // 为固定的顶部导航栏留出空间
          padding: "24px",
          background: "#f5f5f5",
          minHeight: "calc(100vh - 64px)",
        }}
      >
        <div
          style={{
            background: colorBgContainer,
            borderRadius: "8px",
            padding: "24px",
            minHeight: "calc(100vh - 112px)",
          }}
        >
          {children}
        </div>
      </Content>

      {/* 移动端样式 */}
      <style>{`
        .desktop-menu {
          display: ${isMobile ? "none" : "block"} !important;
        }
        
        .mobile-menu-trigger {
          display: ${isMobile ? "block" : "none"} !important;
        }

        @media (max-width: 1200px) {
          .desktop-menu {
            display: none !important;
          }
          
          .mobile-menu-trigger {
            display: block !important;
          }
        }

        .ant-menu-dark.ant-menu-horizontal .ant-menu-item-selected {
          font-weight: bold !important;
          color: white !important;
          border-bottom: 2px solid white !important;
          background: transparent !important;
        }
        .ant-menu-dark.ant-menu-horizontal .ant-menu-item-selected::after {
          border-bottom: 2px solid white !important;
        }
        .ant-menu-dark.ant-menu-horizontal .ant-menu-item-selected .ant-menu-title-content {
          font-weight: bold !important;
          color: white !important;
        }
        .ant-menu-dark.ant-menu-horizontal .ant-menu-item:hover {
          color: rgba(255, 255, 255, 0.9) !important;
        }
      `}</style>
    </AntLayout>
  );
};

export default Layout;
